package com.zhaozhaonews.wemedia.gateway.filter;


import com.zhaozhaonews.wemedia.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author WanJl
 * @version 1.0
 * @title AuthorizeFilter
 * @description 运营端服务全局过滤器
 * @create 2025/2/14
 */
@Component
@Slf4j
public class AuthorizeFilter implements Ordered, GlobalFilter {


    @Override
    public int getOrder() {
        return 0;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1、获取请求对象request和响应对象response
        //获取用户发送的请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取要响应给用户的响应对象response
        ServerHttpResponse response = exchange.getResponse();
        //2、判断是否登录
        if (request.getURI().getPath().contains("/login")){
            //放行
            return chain.filter(exchange);
        }

        //3、如果不是登录，就获取token
        //request.getHeaders()获取请求头，getFirst("token");获取请求头属性名为token的第一个属性值
        String token = request.getHeaders().getFirst("token");

        //4、判断token是否有效
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            //判断这个token是否过期
            //AppJwtUtil.verifyToken(claimsBody)会返回4种结果：-1：token有效，0：token有效，1：token过期，2：token过期
            int result = AppJwtUtil.verifyToken(claimsBody);
            if (result == 1|| result == 2){ //说明过期了
                response.setStatusCode(HttpStatus.UNAUTHORIZED);    //返回响应状态码401
                return response.setComplete();//响应
            }

            //获取token解析后的用户信息
            Object userId = claimsBody.get("id");
            //在请求头header中添加新的信息
            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", userId + "");
            }).build();
            //重置header
            exchange.mutate().request(serverHttpRequest).build();

        }catch (Exception e){
            e.printStackTrace();//执行异常
            response.setStatusCode(HttpStatus.UNAUTHORIZED);    //返回响应状态码401
            return response.setComplete();//响应
        }
        //放行
        return chain.filter(exchange);
    }
}
